package java_thinking.unit_18_IO._18_7;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeSet;

/**
 * @Desc:   文件读写工具类
 * @author: cww
 * @DateTime: 2019/5/15 9:12
 */

public class TextFile extends ArrayList<String> {
    public static String read(String fileName) throws IOException {
        StringBuilder sb = new StringBuilder();
        try {
            //FileReader 不论接收的是fileName还是new File()，内部都是最后调用的同一个构造器
            BufferedReader in = new BufferedReader(new FileReader(new File(fileName).getAbsoluteFile()));
            try {
                String s;
                while ((s = in.readLine()) != null) {
                    sb.append(s);
                    //为每行加上换行符，因为在读的过程中换行符会被去除掉
                    sb.append("\n");
                }
            } finally {
                in.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return sb.toString();
    }

    public static void write(String fileName, String text) throws IOException {
        //File-->File字节流-->字符输出流-->缓存-->PrintWriter
        PrintWriter out = new PrintWriter(new File(fileName).getAbsoluteFile());
        try {
            out.print(text);
        } finally {
            out.close();
        }
    }

    public TextFile(String fileName, String splitter) throws IOException {
        super(Arrays.asList(read(fileName).split(splitter)));
        if (get(0).equals("")) {
            remove(0);
        }
    }

    public TextFile(String fileName) throws IOException {
        this(fileName, "\n");
    }

    public void write(String fileName) {
        try {
            PrintWriter out = new PrintWriter(new File(fileName).getAbsoluteFile());
            try {
                for (String item : this) {
                    out.println(item);
                }
            } finally {
                out.close();
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        String staticFileUrl = "src/maindemo/java/java_thinking/unit_18_IO/_18_7";
        String file = read(staticFileUrl + "/TextFile.java");
        write(staticFileUrl + "/test.txt", file);
        TextFile text = new TextFile(staticFileUrl + "/test.txt");
        text.write(staticFileUrl + "/test2.txt");
        TreeSet<String> words = new TreeSet<>(new TextFile(staticFileUrl + "/TextFile.java", "\\W+"));
        System.out.println(words.headSet("a"));
    }

}
